package com.inwavetech.os.util.request;

import com.inwavetech.os.util.SimpleResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created by jgskin on 2/24/14.
 */
public abstract class HttpRequest {
    private final DefaultHttpClient client;
    private AuthRequestConfigurator authConfigurator;

    public HttpRequest() {
        client = new DefaultHttpClient();
    }

    public HttpRequest(AuthRequestConfigurator authConfigurator) {
        this();
        this.authConfigurator = authConfigurator;
    }

    public SimpleResponse execute(String url) throws BadImplementationException, IOException {
        SimpleResponse simpleResponse = null;

        // try to fetch the response
        HttpResponse response = client.execute(buildMethod(url)); // IoException, BadImplementationException

        // response received. build the simple response
        simpleResponse = new SimpleResponse();
        simpleResponse.code = response.getStatusLine().getStatusCode();
        simpleResponse.body = EntityUtils.toString(response.getEntity()); // IoException

        return simpleResponse;
    }

    private HttpUriRequest buildMethod(String url) throws BadImplementationException {
        HttpUriRequest method = createMethod(url);

        if (authConfigurator != null) {
            method = authConfigurator.configure(method); // BadImplementationException
        }

        return method;
    }

    protected abstract HttpUriRequest createMethod(String url);
}
